package week01.challenge;

import java.io.IOException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author edward
 * @since 2021-06-27
 */
public class XlassModuleManager {

    private Map<String, XlassLoader> modules = new HashMap<>();

    public synchronized XlassLoader loadModule(String name, String... xarPath) throws IOException {
        if (xarPath == null || xarPath.length <= 0) {
            throw new IllegalArgumentException("Empty xar paths");
        }
        XlassLoader xlassLoader = modules.get(name);
        URL[] urls = new URL[xarPath.length];
        for (int i = 0; i < urls.length; i++) {
            urls[i] = Paths.get(xarPath[i]).toUri().toURL();
        }
        if (xlassLoader == null) {
            xlassLoader = new XlassLoader(urls);
            modules.put(name, xlassLoader);
            return xlassLoader;
        }
        xlassLoader.addURL(urls); // 增加 Xlass 依赖
        return xlassLoader;
    }

    public synchronized XlassLoader getModule(String name) {
        XlassLoader loader = modules.get(name);
        return Objects.requireNonNull(loader, "Module [" + name + "] NOT Found");
    }

    public synchronized void unloadModule(String name) {
        modules.remove(name);
    }

    public synchronized void unloadAllModules() {
        modules.clear();
    }
}
